package com.ruoyi.system.service.impl;

import java.io.IOException;
import java.text.ParseException;
import java.util.List;
import com.ruoyi.common.utils.DateUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.CommunityFacilitiesMapper;
import com.ruoyi.system.domain.CommunityFacilities;
import com.ruoyi.system.service.ICommunityFacilitiesService;
import org.springframework.web.multipart.MultipartFile;
import org.apache.poi.ss.usermodel.Row;

/**
 * 周边设施管理Service业务层处理
 *
 * @author ruoyi
 * @date 2024-03-27
 */
@Service
public class CommunityFacilitiesServiceImpl implements ICommunityFacilitiesService
{
    @Autowired
    private CommunityFacilitiesMapper communityFacilitiesMapper;

    /**
     * 查询周边设施管理
     *
     * @param id 周边设施管理主键
     * @return 周边设施管理
     */
    @Override
    public CommunityFacilities selectCommunityFacilitiesById(Long id)
    {
        return communityFacilitiesMapper.selectCommunityFacilitiesById(id);
    }

    /**
     * 查询周边设施管理列表
     *
     * @param communityFacilities 周边设施管理
     * @return 周边设施管理
     */
    @Override
    public List<CommunityFacilities> selectCommunityFacilitiesList(CommunityFacilities communityFacilities)
    {
        return communityFacilitiesMapper.selectCommunityFacilitiesList(communityFacilities);
    }

    /**
     * 新增周边设施管理
     *
     * @param communityFacilities 周边设施管理
     * @return 结果
     */
    @Override
    public int insertCommunityFacilities(CommunityFacilities communityFacilities) throws Exception{
        if (facilityNameExists(communityFacilities.getFacilityName())) {
            throw new Exception("设施已存在");
        }
        return communityFacilitiesMapper.insertCommunityFacilities(communityFacilities);
    }



    /**
     * 修改周边设施管理
     *
     * @param communityFacilities 周边设施管理
     * @return 结果
     */
    @Override
    public int updateCommunityFacilities(CommunityFacilities communityFacilities) throws Exception {
        // 获取当前设施（如果存在）
        CommunityFacilities existingFacility = getByName(communityFacilities.getFacilityName());

        // 如果设施不存在，进行更新操作
        if (existingFacility == null) {
            communityFacilities.setUpdateTime(DateUtils.getNowDate());
            return communityFacilitiesMapper.updateCommunityFacilities(communityFacilities);
        }

        // 设施存在，检查是否为同一设施（通过ID或其他唯一标识比较）
        if (communityFacilities.getId().equals(existingFacility.getId())) {
            // 同一设施，无需修改名称，直接返回成功状态
            return communityFacilitiesMapper.updateCommunityFacilities(communityFacilities); // 或者使用您业务约定的成功状态码
        }

        // 不是同一设施，检查新名称是否已存在
        if (facilityNameExists(communityFacilities.getFacilityName())) {
            // 新名称已存在，抛出异常
            throw new Exception("设施已存在");
        }

        // 新名称未存在，进行插入操作
        return communityFacilitiesMapper.updateCommunityFacilities(communityFacilities);
    }

    // 使用已有的Mapper方法检查指定设施名称是否已存在于数据库中
    private boolean facilityNameExists(String facilityName) {
        return communityFacilitiesMapper.countByName(facilityName) > 0;
    }
    @Override
    public CommunityFacilities getByName(String name) {
        return communityFacilitiesMapper.getFacilitiesByName(name);
    }

    /**
     * 导入功能实现
     * @param file
     * @return
     * @throws IOException
     */
    @Override
    public int importCommunityFacilities(MultipartFile file) throws IOException {
        int rowsAffected = 0;

        // 创建一个 Workbook 对象来读取 Excel 文件
        try (Workbook workbook = new XSSFWorkbook(file.getInputStream())) {
            // 获取第一个工作表
            Sheet sheet = workbook.getSheetAt(0);

            // 遍历工作表中的所有行
            for (Row row : sheet) {
                // 跳过表头行
                if (row.getRowNum() == 0) {
                    continue;
                }

                // 从单元格中提取数据
                String facilityName = getStringCellValue(row, 0);
                String facilityTypeId = getStringCellValue(row, 1);
                String facilityManager = getStringCellValue(row, 2);
                String facilityContact = getStringCellValue(row, 3);
                String phone = getStringCellValue(row, 4);
                String address = getStringCellValue(row, 5);

                // 创建 CommunityFacilities 对象并设置属性
                CommunityFacilities facility = new CommunityFacilities();
                facility.setFacilityName(facilityName);
                facility.setTypeId(Long.parseLong(facilityTypeId));
                facility.setFacilityManager(facilityManager);
                facility.setFacilityContact(facilityContact);
                facility.setPhone(phone);
                facility.setAddress(address);

                // 调用 insertCommunityFacilities 方法插入单个设施
                try {
                    rowsAffected += insertCommunityFacilities(facility);
                } catch (Exception e) {
                    // 记录或处理插入失败的异常（例如记录日志、忽略错误行等）
                }
            }
        }

        return rowsAffected;
    }

    private String getStringCellValue(Row row, int cellIndex) {
        Cell cell = row.getCell(cellIndex);
        return cell != null ? cell.getStringCellValue().trim() : "";
    }


    /**
     * 批量删除周边设施管理
     *
     * @param ids 需要删除的周边设施管理主键
     * @return 结果
     */

    @Override
    public int deleteCommunityFacilitiesByIds(Long[] ids)
    {
        return communityFacilitiesMapper.deleteCommunityFacilitiesByIds(ids);
    }

    /**
     * 删除周边设施管理信息
     *
     * @param id 周边设施管理主键
     * @return 结果
     */
    @Override
    public int deleteCommunityFacilitiesById(Long id)
    {
        return communityFacilitiesMapper.deleteCommunityFacilitiesById(id);
    }
}